package com.curry.log.behavior;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import android.os.AsyncTask;

import com.curry.log.config.AppConfig;
import com.curry.log.dervice.Device;
import com.curry.log.dervice.Environment;
import com.curry.log.dervice.Environment.EnvListener;
import com.curry.log.file.FileHelper;
import com.curry.log.upload.UploadFileTask;

public class BehaviorLog {

	public static final String ACT_CLICK = "click";
	public static final String ACT_DETAIL_IN = "detail.in";
	public static final String ACT_DETAIL_OUT = "detail.out";
	public static final String ACT_BOWESR = "browse";
	public static final String ACT_PHONE = "phone";
	
	public  AppConfig appConfig=null;
	public  static BehaviorLog bl;
	public Device device=null;
	
	/**
	 * 
	 * @param config
	 * @return
	 */
	
	public BehaviorLog(AppConfig config){

		this.appConfig=config;
		initEnv();
	}
	public BehaviorLog(){

	}
	
	public void initEnv(){
		Environment.getSingleton().setEnvironment(appConfig.getContext());
		Environment.getSingleton().setEnvListener(new EnvListener() {

			@Override
			public void request(Environment env) {
				device = new Device(env.getMobilePhone(), env.getDeviceID(), env.getModel(), env.getOsLevel(), env.getDispDpi(), env.getDispHeight(), env.getDispWidth(), appConfig.getMemberID());
			}
		});
	}
	
	public void setMemberID(String memberID){
		appConfig.setMemberID(memberID);
	}
	/**
	 * 
	 * @param action
	 * @param uri
	 * @param commid
	 */
	public void setBehavior(String action, String uri,String commid){
		try {
			FileHelper file=new FileHelper();
			Behavior be=new Behavior(action, uri, new Date().getTime(), commid);
			file.saveLog(be, device);

		} catch (Exception e) {
		}
		
	}

	private Map<String,String> map=new HashMap<String,String>();
	/**
	 * 上传行为记录
	 */
	public void upload(){
		
		FileHelper fh=new FileHelper();
    	String path=fh.getUploadFiles();
    	
    	if(path!=null){
    	String []paths=path.split("#");
    	for(int i=0;i<paths.length;i++){
			if(!map.containsKey(paths[i])) {
				map.put(paths[i],paths[i]);
				UploadFileTask uploadFileTask = new UploadFileTask(appConfig.getContext());
				uploadFileTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (paths[i]));

				}
    		}
    	}
	}

	public  void removeFile(String path){
		new FileHelper().removeFile(path);
		removeMap(path);
	}
	public void removeMap(String path){
		if(map.containsKey(path))
			map.remove(path);
	}
}
